<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

class ToolController extends Controller
{
    /**
     * @param Request $request
     * @param string $name 上传文件的name值
     * @param string $dir 上传文件的路径名
     * @param int $isdate 是否开启日期文件夹保存（默认保存）
     */
    public function upload(Request $request,$name = "typeimg",$dir = "type",$isdate = 1)
    {
        // 检测是否有文件上传
        if ($request->hasFile("$name")) {
            // 微秒时间戳
            $file_name = str_replace(".","",microtime(true)) . mt_rand(1000, 9999);
            // 原始文件后缀
            $type = $request->file("$name")->getClientOriginalExtension();
            if($isdate == 1){
                $date = date("Y-m-d", time()) . "/";
            } else {
                $date = "";
            }

            ///////////////////////
            $qiniu = DB::table("configs")->where("group_id","4")->get();
            $qiniuConfig = array_column(_toArray($qiniu),"value","name");
            if($qiniuConfig['cfg_qiniu'] == 1){
                $upManager = new UploadManager();
                $auth = new Auth($qiniuConfig['cfg_qiniu_AccessKey'], $qiniuConfig['cfg_qiniu_SecretKey']);
                $token = $auth->uploadToken($qiniuConfig['cfg_qiniu_BucketName']);
                list($ret, $error) = $upManager->put($token, 'blog/'.$dir."/".$date.$file_name. "." . $type, file_get_contents($request->$name));
                if($error == null){
                    $arr = array('success'=>1, 'message'=>'上传成功','url'=>$qiniuConfig['cfg_qiniu_url'].$ret['key']);
                } else {
                    $arr = array('success'=>0, 'message'=>'上传失败');
                }
            } else {
                ///////////////////////
                // 移动文件到目录
                $request->file("$name")->move('./upload/' . $dir . "/".$date, $file_name . "." . $type);
                // 返回结果
                $arr = array('success'=>1, 'message'=>'上传成功！', 'url'=>'/upload/' . $dir . "/".$date . $file_name . "." . $type);
            }
        } else {
            $arr = array('state'=>0, 'message'=>'上传失败');
        }
        echo json_encode($arr);
        // dump($request->all());
    }
}
